<template>
    <XTable ref='tableRef' selection :api='iotsimPaginationApi' :columns='columns' @selectionChange='selectionChange'>
        <template #toolBar>
            <el-button type='primary' size='mini' @click='openAdd'>新 增</el-button>
            <XRequestButton isConfirm confirmText='确定删除选中的物联网卡吗' :click='deleteAllIotsim'>
                <el-button type='danger' size='mini'>删除</el-button>
            </XRequestButton>
        </template>

        <template #fee='{value}'>{{value}}元</template>
        <template #expireIn='{value}'>{{parseTime(value, '{y}-{m}-{d}')}}</template>
        <template #action='{row}'>
            <template v-if='row'>
                <XRequestButton class='m-l-5' isConfirm confirmText='确定删除该物联网卡吗' :click='async () => deleteSingleIotsim(row.id)'>
                    <el-button type='text'>删除</el-button>
                </XRequestButton>
                <el-button type='text' class='m-l-5' @click='openEdit(row)'>编辑</el-button>
            </template>
        </template>
    </XTable>

    <el-dialog destroy-on-close v-model='dialogVisible' @closed='closeDialog' :title='(formData.id ? "编辑" : "新增") + "物联网卡"' width='400px'>
        <div>
            <el-form ref='formRef' size='mini' label-width='80px' :rules='rules' :model='formData'>
                <el-form-item label='卡号' prop='cardNo'>
                    <el-input type='text' clearable show-word-limit :maxlength='rules.cardNo[1].len' v-model='formData.cardNo' />
                </el-form-item>
                <el-form-item label='流量费' prop='fee'>
                    <el-input type='text' clearable v-model.number='formData.fee' />
                </el-form-item>
                <el-form-item label='到期时间'>
                    <el-date-picker class='w-100' value-format='YYYY-MM-DD' type='date' v-model='formData.expireIn' />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <el-button size='mini' @click='dialogVisible=false'>取 消</el-button>
            <XRequestButton class='m-l-20' :click='submitIotSim'>
                <el-button size='mini' type='primary'>确 定</el-button>
            </XRequestButton>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup>
    import { onActivated, reactive, ref, toRefs } from 'vue'
    import { iotsimPaginationApi, addIotsimApi, editIotsimApi, deleteIotsimApi } from '../../api/iotsim'
    import { ElMessage } from 'element-plus'
    import { filterEmpty, parseTime } from '../../utils'

    const columns:Column[] = [
        {title : '卡号', dataIndex : 'cardNo', inFilter : true},
        {title : '流量费', dataIndex : 'fee', inFilter : false},
        {title : '到期时间', dataIndex : 'expireIn', inFilter : false},
        {title : '到期时间', dataIndex : 'expireRange', inFilter : true, hideInTable : true, filter : {
            type : 'daterange',
            transform(value){
                if(value) {
                    return {startDate : value[0], endDate : value[1]}
                }
                return null
            }
        }},
    ]


    const formData = reactive<{
        cardNo : string,
        expireIn : string,
        fee : number | '',
        id : number
    }>({
        cardNo : '',
        expireIn : '',
        fee : '',
        id : 0
    })

    const rules = reactive({
        cardNo : [
            {
                required : true,
                message : '请输入卡号'
            },
            {
                len : 20,
                message: '请输入卡号长度为20个字符',
            }
        ],

        fee : [
            {
                type : 'number',
                min : 0,
                max : 1000,
                message : '流量费在0-1000元之间'
            }
        ]
    })

    let selectedIds = reactive([])
    const formRef = ref()    
    const tableRef = ref()
    const isFirst = ref(true)
    const dialogVisible = ref(false)

    function selectionChange(rows:any[]) {
        selectedIds.splice(0)
        selectedIds.push(...rows.map(row => row.id))
    }

    function openAdd() {
        dialogVisible.value = true
    }

    function openEdit(row:any) {
        formData.cardNo = row.cardNo
        formData.expireIn = parseTime(row.expireIn)
        formData.fee = Number(row.fee)
        
        formData.id = row.id
        dialogVisible.value = true
    }

    function closeDialog() {
        formData.cardNo = ''
        formData.expireIn = ''
        formData.id = 0
    }

    async function submitIotSim() {
        let data = {...formData}
        try {
            await formRef.value.validate()
            if(!formData.id) {
                filterEmpty(data)
                const res = await addIotsimApi(data)
                if(res.success) {
                    tableRef.value.load()
                    dialogVisible.value = false
                    closeDialog()
                    ElMessage.success!('增加成功')
                }else {
                    ElMessage.error!(res.msg)
                }
            }else {
                data.fee = 0
                const res = await editIotsimApi(formData.id, data)
                if(res.success) {
                    tableRef.value.load()
                    dialogVisible.value = false
                    closeDialog()
                    ElMessage.success!('编辑成功')
                }else {
                    ElMessage.error!(res.msg)
                }
            }
            
            
        } catch (error) {
            
        }
    }

    async function deleteAllIotsim() {
        await deleteIotsim(selectedIds)
    }

    async function deleteSingleIotsim(id:number) {
        await deleteIotsim([id])
    }

    async function deleteIotsim(ids:number[]) {
        const res = await deleteIotsimApi(ids)
        if(res.success) {
            tableRef.value.load()
            ElMessage.success!('删除成功')
        }else {
            ElMessage.error!(res.msg)
        }
    }

    onActivated(() => {
        if(isFirst.value) {
            isFirst.value = false
        }else {
            tableRef.value.load()
        }
    })

</script>